<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Application;
use App\Models\Project;
use App\Models\ProjectInvoice;
use App\Services\ProjectService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectInvoiceController extends Controller
{

    protected $ProjectService;
    public function __construct(ProjectService $ProjectService)
    {
        $this->ProjectService = $ProjectService;
    }

    public function index(Request $Request)
    {
        $data = ProjectInvoice::where('user_id',Auth::user()->id)->with('application')->with('project')->where('project_id',$Request->project_id)->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function last(Request $Request)
    {
        $data = ProjectInvoice::where('project_id',$Request->project_id)->orderBy('id','desc')->first();
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function show(Request $Request)
    {
        $data = ProjectInvoice::with('application')->with('project')->where('id',$Request->id)->first();
        $project = Project::select('id','title','status','price','tax_rate')->where('id',$Request->project_id)->first();

        //查询累计开票金额
        if($data){

            $data->is = true;
            if($data->application){
                $data->is = $data->application->status != 'rejected' ? false : true;
            }
        }

        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data,'project'=>$project,'invoice_amount'=>$data->invoice_amount]);
    }

    public function store(Request $Request)
    {
        $POSTONLY = ProjectInvoice::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['user_id'] = Auth::user()->id;
        $data = $this->ProjectService->insertProjectInvoice($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function update(Request $Request)
    {
        $POSTONLY = ProjectInvoice::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['id'] = $Request->id;
        $data = $this->ProjectService->updateProjectInvoice($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的记录']);
        }
        $data = ProjectInvoice::find($Request->id);
        $data->delete();
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }
}
